package com.example.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-11-16
 * Time: 10:14
 */
@RestController
@RequestMapping("/header")
public class HeaderController {
    @RequestMapping("/print1")//获取多个cookies
    public String print1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            return "没有cookie";
        }
        for(Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        }
        return "成功获取cookie值";
    }

    @RequestMapping("/print2")
    public String print2(@CookieValue("jianke") String name) {
        return "从Cookie中获取信息： " + name;
    }

    @RequestMapping("/print3")//设置session
    public String print3(HttpServletRequest request) {
        HttpSession session = request.getSession();
        //默认ture，当里面的布尔参数为true时，如果session对象为空，创建一个空的session，否则，session对象为null
        session.setAttribute("userName","wangwu");
        session.setAttribute("age",18);
        return "创建session成功";
    }

    @RequestMapping("/print4")//获取session的第一种方法
    public String print4(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session == null) {
            return "session is null";
        }
        String userName = (String)session.getAttribute("userName");
        Integer age = (Integer)session.getAttribute("age");
        return "session获取成功,userName: " + userName+" " + "age: " + age;
    }


    @RequestMapping("/print5")//获取session的第二种方法
    public String print5(HttpSession session) {
        String userName = (String)session.getAttribute("userName");
        Integer age = (Integer)session.getAttribute("age");
        return "session获取成功,userName: " + userName+" " + "age: " + age;
    }

    @RequestMapping("/print6")//获取session的第三种方法：对session要求更严格，如果session为null则不会进入方法
    public String print6(@SessionAttribute("userName") String userName,@SessionAttribute("age") Integer age) {
        return "session获取成功,userName: " + userName+" " + "age: " + age;
    }

    @RequestMapping("/print7")
    public String print7(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }

    @RequestMapping("/print8")
    public String print8(@RequestHeader("User-Agent") String userAgent) {
        return userAgent;
    }

}
